package nccloud.riart.pub.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Properties;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.common.RuntimeEnv;
import nc.bs.logging.Logger;
import nc.md.model.MetaDataException;
import nc.md.persist.framework.IMDPersistenceQueryService;
import nc.pubitf.para.SysInitQuery;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.sm.UserVO;

public class HttpUtil {

    /**
     * 修改时间戳
     * @param defdocVO
     * @throws Exception
     */
    public static int updateVO(DefdocVO defdocVO) throws Exception {
        BaseDAO dao = new BaseDAO();
        defdocVO.setStatus(VOStatus.UPDATED);
        int updateVO = dao.updateVO(defdocVO);
        return updateVO;
    }
    /**
     * 推送数据导考勤系统
     * @param api
     * @param param
     * @param entityName
     * @return
     * @throws BusinessException
     */
    public static boolean sendPost(String api, String param,String entityName) throws BusinessException {
        Writesendlog log = new Writesendlog();
        String url = SysInitQuery.getParaString("GLOBLE00000000000000", "QLZKHRurl");
        String hrhiACCESS_KEY = SysInitQuery.getParaString("GLOBLE00000000000000", "QLZKHRkey");
        url = url+api+"?key="+hrhiACCESS_KEY;
        log.writesendlog(param.toString()+";;;;;;;;;"+url, entityName+"shuju", "");
        String result = "";
        CloseableHttpClient httpClient =  HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            HttpPost httppost = new HttpPost(url);
            httppost.setHeader("Accept", "application/json");
            httppost.setHeader("Content-Type","application/x-www-form-urlencoded");
            BasicHttpEntity requestBody = new BasicHttpEntity();
            requestBody.setContent(new ByteArrayInputStream(param.getBytes("UTF-8")));
            requestBody.setContentLength(param.getBytes("UTF-8").length);
            httppost.setEntity(requestBody);
            response = httpClient.execute(httppost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionUtils.wrappBusinessException(entityName+":"+ e.getMessage());
        }finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            log.writesendlog(result, entityName+"返回结果" , "");
            if(!"".equals(result)) {
                JSONObject parseObject = JSONObject.parseObject(result);
                Object object = parseObject.get("ret");
                log.writesendlog(parseObject.toString(), entityName + "返回状态", "");
                if(!"".equals(object)&& object != null) {
                    int parseInt = Integer.parseInt(object.toString());
                    if(parseInt != 0) {
                        log.writesendlog(param, entityName + "返回结果", "");
                        if(parseInt == 1) {
                            return false;
                        }else {
                            return true;
                        }
                    }else {
                        return true;
                    }
                }
            }
        }
        return  false;
    }
    /**
     * 获取token
     *
     */
    public static String gettokenPost(String appKey, String appId) throws BusinessException, KeyManagementException, IOException, NoSuchAlgorithmException, NoSuchProviderException {
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        trustManagers = new TrustManager[] { new DefaultTrustManager()};
        SSLContext context = SSLContext.getInstance("TLSv1.2");
        context.init(keyManagers, trustManagers, null);
        SSLSocketFactory sslFactory = context.getSocketFactory();

        StringBuilder url = new StringBuilder(
                SysInitQuery.getParaString("GLOBLE00000000000000", "QLBSUrl") + "/token");
        URL realUrl = new URL(url.toString());
        HttpsURLConnection httpsConn = (HttpsURLConnection) realUrl.openConnection();
        OutputStreamWriter out = null;
        httpsConn.setSSLSocketFactory(sslFactory);
        httpsConn.setDoInput(true);
        httpsConn.setDoOutput(true);
        httpsConn.setRequestProperty("accept", "*/*");
        httpsConn.setRequestProperty("connection", "Keep-Alive");
        httpsConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

        httpsConn.setRequestMethod("POST");
        httpsConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("grant_type", "client_credentials");
        jsonObject.put("appKey", appKey);
        jsonObject.put("appId", appId);
        NameValuePair[] data = {
                new NameValuePair("grant_type", "client_credentials"),
                new NameValuePair("appKey", appKey),
                new NameValuePair("appId", appId)
        };
        StringBuilder postData = new StringBuilder();
        postData.append(URLEncoder.encode("grant_type", "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode("client_credentials", "UTF-8"));
        postData.append('&');
        postData.append(URLEncoder.encode("app_key", "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(appKey, "UTF-8"));
        postData.append('&');
        postData.append(URLEncoder.encode("app_secret", "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(appId, "UTF-8"));
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");
        httpsConn.connect();
        httpsConn.getOutputStream().write(postDataBytes);
        out = new OutputStreamWriter(httpsConn.getOutputStream(), "UTF-8");
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(), "UTF-8"));
        String line;
        StringBuffer rt = new StringBuffer();
        while ((line = in.readLine()) != null) {
            rt.append(line);
        }
        String result = rt.toString();
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
        JSONObject parseObject = JSONObject.parseObject(result);
        Object object = parseObject.get("access_token");
        return object.toString();
    }

    /**
     * 北森接口发送
     */
    public static String httpPostData(String url, String token, String parem, String entityName) throws BusinessException, KeyManagementException, IOException, NoSuchAlgorithmException, NoSuchProviderException{
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;
        trustManagers = new TrustManager[] { new DefaultTrustManager()};
        SSLContext context = SSLContext.getInstance("TLSv1.2");
        context.init(keyManagers, trustManagers, null);
        SSLSocketFactory sslFactory = context.getSocketFactory();
        StringBuilder url1 = new StringBuilder(
                SysInitQuery.getParaString("GLOBLE00000000000000", "QLBSDUrl") + url);
        URL realUrl = new URL(url1.toString());
        HttpsURLConnection httpsConn = (HttpsURLConnection) realUrl.openConnection();
        OutputStreamWriter out = null;
        httpsConn.setSSLSocketFactory(sslFactory);
        httpsConn.setDoInput(true);
        httpsConn.setDoOutput(true);
        httpsConn.setRequestProperty("authorization", "Bearer " + token);
        httpsConn.setRequestProperty("accept", "*/*");
        httpsConn.setRequestProperty("connection", "Keep-Alive");
        httpsConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

        httpsConn.setRequestMethod("POST");
        httpsConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpsConn.connect();
        out = new OutputStreamWriter(httpsConn.getOutputStream(), "UTF-8");
        out.append(parem);
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(),"UTF-8"));
        String line;
        StringBuffer rt = new StringBuffer();
        while ((line = in.readLine()) != null) {
            rt.append(line);
        }
        String result=rt.toString();
        Writesendlog log = new Writesendlog();
        log.writesendlog(result, entityName+"返回结果", "");
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        log.writesendlog(result, entityName, "");
        return result;
    }
    /**
     * 中控考勤接口发送
     * @param api
     * @param param
     * @param entityName
     * @return
     * @throws BusinessException
     */
    public static String httpPost(String api, String param,String entityName) throws BusinessException {
        String url = SysInitQuery.getParaString("GLOBLE00000000000000", "QLZKHRurl");
        String hrhiACCESS_KEY = SysInitQuery.getParaString("GLOBLE00000000000000", "QLZKHRkey");
        url = url+api+"?key="+hrhiACCESS_KEY;
        String result = "";
        CloseableHttpClient httpClient =  HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            HttpPost httppost = new HttpPost(url);
            httppost.setHeader("Accept", "application/json");
            httppost.setHeader("Content-Type","application/x-www-form-urlencoded");
            BasicHttpEntity requestBody = new BasicHttpEntity();
            requestBody.setContent(new ByteArrayInputStream(param.getBytes("UTF-8")));
            requestBody.setContentLength(param.getBytes("UTF-8").length);
            httppost.setEntity(requestBody);
            // 执行客户端请求
            response = httpClient.execute(httppost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            //自动释放链接
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            Writesendlog log = new Writesendlog();
            // 关闭连接
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(!"".equals(result)) {
                JSONObject parseObject = JSONObject.parseObject(result);
                Object object = parseObject.get("ret");
                log.writesendlog(parseObject.toString(), entityName + "返回结果", "");
                if(!"".equals(object)&& object != null) {
                    int parseInt = Integer.parseInt(object.toString());
                    if(parseInt != 0) {
                        log.writesendlog(param, entityName + "返回结果", "");
                        return "";
                    }else {
                        Object object2 = parseObject.get("data");
                        if(!"".equals(object2)&& object2 != null) {
                            JSONObject parseObject2 = JSONObject.parseObject(object2.toString());
                            return parseObject2.get("items").toString();
                        }
                    }
                }
            }
        }
        return  "";
    }

    /**
     * 推送数据到统一认证平台
     * @param api
     * @param param
     * @param entityName
     * @return
     * @throws BusinessException
     * @throws IOException
     */
    public static String sendUamPost(String api, String param,String type ,String entityName) throws BusinessException, IOException {
        Properties properties = HttpUtil.getNccUrlInfo();
        String qzj = properties.get("lw").toString();
        String url1 = "http://"+qzj+api;
//        String url1 = "http://192.168.104.141:8011"+api;
        Writesendlog log = new Writesendlog();
        URL url = new URL(url1);
        URLConnection uc = url.openConnection();
        uc.setDoOutput(true);
        uc.setUseCaches(false);
        uc.setRequestProperty("Content-Type","application/json");
        uc.setRequestProperty("Charset", "UTF-8");
        uc.setRequestProperty("Content-Length", "10000");
        HttpURLConnection hc = (HttpURLConnection) uc;
        hc.setRequestMethod(type);
        hc.setRequestProperty("Charsert", "UTF-8");
        OutputStream os = null;
        DataOutputStream dos = null;
        String result = "";
        try {
            os = hc.getOutputStream();
            dos = new DataOutputStream(os);
            dos.write(param.getBytes());
            dos.flush();
            BufferedReader bReader = new BufferedReader(new InputStreamReader(hc.getInputStream(),"UTF-8"));
            int ch;
            while ((ch = bReader.read()) != -1) {
                result += String.valueOf((char) ch);
            }
        }catch(Exception e) {
            Logger.error(e.getMessage(), e);
            ExceptionUtils.wrappBusinessException(entityName+":"+ e.getMessage());
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (Exception e2) {
                    Logger.error(e2.getMessage(), e2);
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e2) {
                    Logger.error(e2.getMessage(), e2);
                }
            }
            if(!"".equals(result)&&result!=null) {
                JSONObject parseObject = JSONObject.parseObject(result);
                Object object = parseObject.get("code");
                if(!"".equals(object)&&object!=null) {
                    int parseInt = Integer.parseInt(object.toString());
                    if(parseInt == 0) {
                        log.writesendlog(param+"返回值"+result, entityName+"chenggong","");
                        return result;
                    }
                }
                log.writesendlog(url1+";;type:"+type+";;;数据:"+param+";;;返回值"+result, entityName+"error","");
            }else {
                log.writesendlog(url1+";;type:"+type+";;;数据:"+param+";;;返回值"+result, entityName+"error","");
            }
        }
        return  result;
    }
    public static boolean analysisResult(String result) {
        if(!"".equals(result)&&result!=null) {
            JSONObject parseObject = JSONObject.parseObject(result);
            Object object = parseObject.get("code");
            if(!"".equals(object)&&object!=null) {
                int parseInt = Integer.parseInt(object.toString());
                if(parseInt == 200) {
                    return true;
                }
            }
        }else {
            return false;
        }
        return false;
    }
    //Unicode码转中文
    private static String unicodeToCn(String unicode) {
        /** 以 \ u 分割，因为java注释也能识别unicode，因此中间加了一个空格*/
        String[] strs = unicode.split("\\\\u");
        String returnStr = "";
        // 由于unicode字符串以 \ u 开头，因此分割出的第一个字符是""。
        for (int i = 1; i < strs.length; i++) {
            returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
        }
        return returnStr;
    }
    public static UserVO getCodeByUserPk(String pk_user) throws MetaDataException {
        IMDPersistenceQueryService service = NCLocator.getInstance().lookup(IMDPersistenceQueryService.class);
        UserVO userVO = ((List<UserVO>) service.queryBillOfVOByCond(UserVO.class,"cuserid = '" + pk_user + "' and dr = 0", false)).get(0);
        return userVO;
    }
    /**
     * 获取NCC的url信息
     * @return
     */
    public static Properties getNccUrlInfo() {
        String homePath = RuntimeEnv.getInstance().getNCHome();
        String oaPath = null;
        homePath = homePath.replace("\\", "/");
        if (!homePath.endsWith("/")) {
            homePath += "/";
        }
        oaPath = homePath + "resources/sso.properties";
        Properties oaProperties = new Properties();
        try {
            oaProperties.load(new FileInputStream(oaPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return oaProperties;
    }
    private static final class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }
}
